package com.health.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.health.constant.MessageConstant;
import com.health.constant.RedisConstant;
import com.health.entity.QueryPageBean;
import com.health.entity.Result;
import com.health.pojo.Setmeal;
import com.health.service.SetmealService;
import com.health.utils.QiniuUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Reference
    private SetmealService setmealService;
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/upload.do")
    public Result upload(@RequestParam("imgFile") MultipartFile imgFile){
        System.out.println(imgFile);
        String originalFilename=imgFile.getOriginalFilename();
        int index=originalFilename.lastIndexOf(".");
        String extention=originalFilename.substring(index);
        String fileName= UUID.randomUUID().toString()+extention;
        try {
            QiniuUtils.upload2Qiniu(imgFile.getBytes(),fileName);
            redisTemplate.boundSetOps(RedisConstant.SETMEAL_PIC_RESOURCES).add(fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
        }
        return new Result(true,MessageConstant.PIC_UPLOAD_SUCCESS,fileName);
    }

    @PostMapping("/add.do")
    public Result add(@RequestBody Setmeal setmeal, Integer[] checkgroupIds){
        try {
            setmealService.add(setmeal,checkgroupIds);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.ADD_SETMEAL_FAIL);
        }
        return new Result(true,MessageConstant.ADD_SETMEAL_SUCCESS);
    }

    @RequestMapping("/findPage.do")
    public Result findPage(@RequestBody QueryPageBean queryPageBean){
        Page<Setmeal> page=setmealService.pageQuery(queryPageBean.getCurrentPage(),queryPageBean.getPageSize(),queryPageBean.getQueryString());
        return new Result(true,MessageConstant.QUERY_CHECKITEM_SUCCESS,page);
    }
}
